package ui.util
{
		import flash.display.Bitmap;
		import flash.display.BitmapData;
		import flash.display.Loader;
		import flash.events.Event;
		import flash.events.EventDispatcher;
		import flash.events.IOErrorEvent;
		import flash.net.URLRequest;
		
		[Event(name=COMPLETE, type="flash.events.Event")]
		[Event(name=FAULT, type="flash.events.IOErrorEvent")]
		
		/**
		 * Util class used for loading images into BitmapData or an Array of BitmapData.
		 * 
		 * <pre>
		 * Use as:
		 * 1. loadBitmapData(String) or loadAllBitmapData(Array)
		 * 2. Wait for an Event.COMPLETE (you can also listen for an IO_ERROR event)
		 * 3. get your data using bitmapData or bitmapDataArray
		 * </pre> 
		 */
		public class BitmapDataLoader extends EventDispatcher
		{
			private var bitmapLoader:Loader;
			private var bitmapRequest:URLRequest;
			
			protected var _bitmapDataArray:Array;
			protected var url:Array;
			protected var size:int;
			
			public function BitmapDataLoader() {}
			
			public function loadBitmapData(url:String):void {
				bitmapLoader = new Loader();
				bitmapLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, eventOnComplete);
				bitmapLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, eventOnError);
				
				bitmapRequest = new URLRequest(url);
				bitmapLoader.load(bitmapRequest);
			}
			//TODO Trivial priority: add method comments
			public function loadAllBitmapData(array:Array):void {
				url = array;
				size = array.length;
				_bitmapDataArray = new Array();
				
				loadNext();
			}
			
			protected function loadNext():void {
				loadBitmapData(url[url.length - size]);
			}
			
			protected function eventOnComplete(event:Event):void {
				var imageLoader:Loader = Loader(event.target.loader);
				var imageBitmap:Bitmap = Bitmap(imageLoader.content);
				
				clean();
				if (url != null) {
					_bitmapDataArray[_bitmapDataArray.length] = imageBitmap.bitmapData;
					if (--size > 0) {
						loadNext();
					} else {
						url = null;
						dispatchEvent(event);
					}
				} else {
					dispatchEvent(new BitmapEvent(imageBitmap.bitmapData));
				}
			}
			
			protected function clean():void {
				bitmapLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, eventOnComplete);
				bitmapLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, eventOnError);
				bitmapLoader.unload();
			}
			
			private function eventOnError(event:IOErrorEvent):void {
				clean();
				url = null;
				dispatchEvent(event);
			}
		}
	}